import { CloseOutlined } from "@ant-design/icons"
import { Button, Card, Input, Form, message } from "antd"
import React, { useCallback, useEffect, useState } from "react"
import { ModalRef } from "../modal.context"
import eventBus from "@/utils/event.bus"
import { DatePicker } from "antd"
import moment from "moment"
import checkImage from "@/utils/checkImage.func"
import FormUploads from "@/components/form/form.uploads"
import serviceManage from "@/services/service.manage"
import urlFunc from "@/utils/url.func"
import { addFlowpathParams } from "@/interfaces/params.interface"

const { RangePicker } = DatePicker

interface Props {
	id: string
}
const AddFlowpathModal: React.FC<Props & ModalRef> = props => {
	const { modalRef, id } = props
	const { TextArea } = Input
	const [form] = Form.useForm()
	const exhibitionId = location.search.split("exhibitionId=")[1]
	const [done, setDone] = useState(false)
	const [lock, setLock] = useState(false)
	const [params, getParams] = useState<addFlowpathParams>()
	const closeModal = useCallback(() => {
		modalRef.current.destroy()
	}, [])

	useEffect(() => {
		if (!!lock) {
			console.log(params)
			serviceManage[!!id ? "updataFlowpath" : "addFlowpath"](params).then(res => {
				if (res.code === 200) {
					eventBus.emit("doFlowpathList")
					modalRef.current.destroy()
					message.success(id ? "修改成功" : "新增成功")
				}
			})
		}
	}, [lock])
	const onFinish = useCallback(data => {
		const param = !!id
			? {
					...data,
					startTime: moment(new Date(data["time"][0])).format("YYYY-MM-DD HH:mm:ss"),
					endTime: moment(new Date(data["time"][1])).format("YYYY-MM-DD HH:mm:ss"),
					image: data.image[0] ? data.image[0].fileSaveUrl : "",
					exhibitionId,
					id
			  }
			: {
					...data,
					startTime: moment(new Date(data["time"][0])).format("YYYY-MM-DD HH:mm:ss"),
					endTime: moment(new Date(data["time"][1])).format("YYYY-MM-DD HH:mm:ss"),
					image: data.image[0] ? data.image[0].fileSaveUrl : "",
					exhibitionId
			  }
		delete param.time
		getParams(param)

		setLock(true)
	}, [])
	const [dates, setDates] = useState([])
	const [hackValue, setHackValue] = useState()
	const [value, setValue] = useState()
	const disabledDate = (current: any) => {
		if (!dates || dates.length === 0) {
			return false
		}
		const tooLate = dates[0] && current.diff(dates[0], "days") > 0
		const tooEarly = dates[1] && dates[1].diff(current, "days") > 0
		return tooEarly || tooLate
	}

	const formatFile = (url: any) => {
		console.log(url)
		if (url instanceof Array) {
			const arr: { filePreviewUrl: string; fileSaveUrl: string; fileSize: number }[] = []
			url.forEach(item => {
				arr.push({
					filePreviewUrl: `${urlFunc.replaceUrl(item.url, "imageUrl")}`,
					fileSaveUrl: item.url,
					fileSize: 0
				})
			})
			return arr
		} else {
			return [
				{
					filePreviewUrl: `${urlFunc.replaceUrl(url, "imageUrl")}`,
					fileSaveUrl: url,
					fileSize: 0
				}
			]
		}
	}
	const onOpenChange = (open: any) => {
		if (open) {
			setHackValue([])
			setDates([])
		} else {
			setHackValue(undefined)
		}
	}

	useEffect(() => {
		if (id) {
			serviceManage.getFlowpathList({ id, exhibitionId }).then(res => {
				if (res.code === 200) {
					console.log(res.data)

					console.log(res.data.entities[0].image)
					form.setFieldsValue({
						...res.data.entities[0],
						time: [
							res.data.entities[0].startTime ? moment(res.data.entities[0].startTime) : null,
							res.data.entities[0].endTime ? moment(res.data.entities[0].endTime) : null
						],
						image: !!res.data.entities[0].image ? formatFile(res.data.entities[0].image) : null
					})
					setDone(true)
				}
			})
		} else {
			setDone(true)
		}
	}, [])
	return (
		done && (
			<Card
				style={{ width: 530 }}
				title={props.id == "" ? "新增展会流程" : "编辑展会流程"}
				extra={
					<Button type="text" onClick={closeModal}>
						<CloseOutlined />
					</Button>
				}
			>
				<Form layout="horizontal" labelCol={{ span: 4 }} form={form} preserve={false} onFinish={onFinish}>
					<Form.Item label="议程时间：" name="time" rules={[{ required: true, message: "请选择议程时间" }]}>
						<RangePicker
							value={hackValue || value}
							disabledDate={disabledDate}
							onCalendarChange={val => setDates(val)}
							onChange={val => setValue(val)}
							onOpenChange={onOpenChange}
							showTime
						/>
					</Form.Item>
					<Form.Item label="议题：" name="content" rules={[{ required: true, message: "请输入议题内容" }]}>
						<TextArea showCount maxLength={50} />
					</Form.Item>
					<Form.Item label="上传封面图：" extra="文件大小5M之内，分辨率830*465jpg、png" name="image">
						<FormUploads
							accept=".png, .jpg, .jpeg"
							customCheck={checkImage("image", 5)}
							checkType={"hotImage"}
							imgAction={{ crop: true, aspectRatio: [830, 465] }}
						></FormUploads>
					</Form.Item>

					<Form.Item style={{ textAlign: "right" }}>
						<Button type="primary" htmlType="submit">
							保存
						</Button>
						<Button style={{ marginLeft: 10 }} htmlType="button" onClick={closeModal}>
							取消
						</Button>
					</Form.Item>
				</Form>
			</Card>
		)
	)
}

export default AddFlowpathModal
